/*
 * Copyright 2010 Matt Oliveri
 *
 * This file is part of JConfigGen
 *
 * JConfigGen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JConfigGen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JConfigGen.  If not, see <http://www.gnu.org/licenses/>.
 */

package atma.jconfiggen.sax;

import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

final class AttrMatcher
{
	static class Match
	{
		final String[] match;
		final int extc;
		final int[] extv;

		Match(String[] m,int c,int[] v) {match = m;extc = c;extv = v;}
	}

	private final String tag;
	private final int n;
	private final HashMap<String,Integer> m = new HashMap<String,Integer>(11);

	AttrMatcher(String t,String... lnms)
	{
		tag = t;
		n = lnms.length;
		for (int i = 0;i < n;++i) m.put(lnms[i],i);
	}

	String[] match(Locator loc,Attributes attr) throws SAXException
	{
		String[] rtn = new String[n];
		for (int i = 0,l = attr.getLength();i < l;++i)
		{
			String ns = attr.getURI(i);
			String at = attr.getLocalName(i);
			if (ns.equals(""))
			{
				Integer j = m.get(at);
				if (j == null) SAXHandler.complain(loc,tag + ": Unexpected attribute \"" + at + '"');
				else rtn[j] = attr.getValue(i);
			}
			else SAXHandler.complain(loc,tag + ": Unexpected attribute \"" + at + "\" in namespace \"" + ns + '"');
		}
		return rtn;
	}

	Match matchExt(Locator loc,Attributes attr) throws SAXException
	{
		int l = attr.getLength();
		String[] rtn = new String[n];
		int c = 0;
		int[] v = new int[l];
		for (int i = 0;i < l;++i)
		{
			String ns = attr.getURI(i);
			String at = attr.getLocalName(i);
			if (ns.equals(""))
			{
				Integer j = m.get(at);
				if (j == null) v[c++] = i;
				else rtn[j] = attr.getValue(i);
			}
			else SAXHandler.complain(loc,tag + ": Unexpected attribute \"" + at + "\" in namespace \"" + ns + '"');
		}
		return new Match(rtn,c,v);
	}
}
